<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="150px">
      <el-form-item label="账户信息" prop="accountName">
        <el-input
          v-model="queryParams.accountName"
          placeholder="请输入账户信息"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="摘要" prop="abstracts">
        <el-input
          v-model="queryParams.abstracts"
          placeholder="请输入摘要"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
          v-model="daterangeFlowDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="账户有无问题" prop="isAccount">
        <el-select v-model="queryParams.isAccount" placeholder="请选择账户有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注有无问题" prop="isRemark">
        <el-select v-model="queryParams.isRemark" placeholder="请选择备注有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据整体有无问题" prop="noWrong">
        <el-select v-model="queryParams.noWrong" placeholder="请选择导入有无问题" clearable>
          <el-option label="有问题" value="0" />
          <el-option label="无问题" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['work:flow:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['work:flow:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['work:flow:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button 
          type="info" 
          plain 
          icon="Upload" 
          size="mini" 
          @click="handleImport" 
          v-hasPermi="['work:flow:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['work:flow:export']"
        >导出</el-button>
      </el-col>
      <RightToolbar :showSearch="showSearch" @queryTable="getList"></RightToolbar>
    </el-row>

    <el-table v-loading="loading" :data="flowList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" width="55" align="center" prop="ids" />
      <el-table-column label="账户信息" align="center" prop="accountName" />
      <el-table-column label="日期" align="center" prop="flowDate" width="180" />
      <el-table-column label="摘要" align="center" prop="abstracts" />
      <el-table-column label="借方" align="center" prop="flowBorrow" />
      <el-table-column label="贷方" align="center" prop="flowLoan" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="二级" align="center" prop="level2Flow" />
      <el-table-column label="数据有无问题" align="center" prop="noWrong" >
        <template #default="scope">
          <span>{{ scope.row.noWrong === '0' ? '有问题' : (scope.row.noWrong === '1' ? '没问题' : scope.row.noWrong) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['work:flow:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['work:flow:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改总流水对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <div v-if="form.noWrong==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前页面整体都没有问题，可以正常使用！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前页面存在不标准数据类型，请尽快修改！
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典账户" prop="accountId">
              <el-select v-model="form.accountId" placeholder="请选择字典账户" filterable @change="handleAccountChange">
                <el-option
                  v-for="account in accountOptions"
                  :key="account.ids"
                  :label="account.accountName"
                  :value="account.ids"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入账户" prop="accountName">
              <el-input v-model="form.accountName" placeholder="请输入导入账户" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isAccount==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前账户名称与字典账户一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前账户名称与字典账户不一致！
            </div> 
          </el-col>
          <el-col :span="12">
            <el-form-item label="流水日期" prop="flowDate">
              <el-date-picker clearable
                v-model="form.flowDate"
                type="date"
                value-format="yyyy年M月d日"
                placeholder="请选择流水日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="摘要" prop="abstracts">
              <el-input v-model="form.abstracts" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借方" prop="flowBorrow">
              <el-input-number v-model="form.flowBorrow" placeholder="请输入借方" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷方" prop="flowLoan">
              <el-input-number v-model="form.flowLoan" placeholder="请输入贷方" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典备注" prop="remarkId">
              <el-select v-model="form.remarkId" placeholder="请选择字典备注" filterable @change="handleRemarkChange" >
                <el-option
                  v-for="dict in remarkOptions"
                  :key="dict.ids"
                  :label="dict.dictName"
                  :value="dict.ids"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导入备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入内容" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div v-if="form.isRemark==='1'" style="color:blue;margin:5px auto; display: block; text-align: center">
              注意：当前备注与字典备注一致！
            </div>
            <div v-else style="color:red;margin:5px auto; display: block; text-align: center">
              注意：当前备注与字典备注不一致！
            </div>     
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级" prop="level2Flow">
              <el-input-number v-model="form.level2Flow" placeholder="请输入二级" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.titleImport" v-model="upload.openImport" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.openImport = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Flow">
import { ref, reactive, onMounted } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import { getToken } from "@/utils/auth";
import { listFlow, getFlow, delFlow, addFlow, updateFlow } from "@/api/work/flow"
import { findYwDictList } from "@/api/work/ywDict"
import { findAllAccountList } from "@/api/work/account"

const { proxy } = getCurrentInstance();

const flowList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const open = ref(false);
const daterangeFlowDate = ref([]);
const accountOptions = ref([]);
const remarkOptions = ref([]);
const queryFormRef = ref();
const formRef = ref();
const uploadRef = ref();

const data = reactive({
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountName: null,
    isAccount: null,
    flowDate: null,
    abstracts: null,
    remark: null,
    isRemark: null,
    noWrong: null,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    accountId: [
      { required: true, message: "字典账户不能为空", trigger: "blur" }
    ],
    accountName: [
      { required: true, message: "账户信息不能为空", trigger: "blur" }
    ],
    flowDate: [
      { required: true, message: "日期不能为空", trigger: "blur" }
    ],
    abstracts: [
      { required: true, message: "摘要不能为空", trigger: "blur" }
    ],
    remarkId: [
      { required: true, message: "字典备注不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
    flowBorrow: [
      { 
        validator: (rule, value, callback) => {
          if (!data.form.flowBorrow && !data.form.flowLoan) {
            callback(new Error('借方和贷方不能同时为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    flowLoan: [
      {
        validator: (rule, value, callback) => {
          if (!data.form.flowBorrow && !data.form.flowLoan) {
            callback(new Error('借方和贷方不能同时为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  },
  // 导入参数
  upload: {
    openImport: false,
    titleImport: "",
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: "Bearer " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/work/flow/importData"
  }
});

const { queryParams, form, rules, upload } = toRefs(data);

/** 获取账户类型选项 */
function getAccountOptions() {
  findAllAccountList().then(response => {
    accountOptions.value = response.data || [];
  });
}

/** 字典流水类型选择变更处理 */
function handleAccountChange(value) {
  const selectedAccount = accountOptions.value.find(item => item.ids === String(value));
  if (selectedAccount) {
    form.value.accountName = selectedAccount.accountName;
    form.value.isAccount = '1';
  } else {
    form.value.accountName = '';
    form.value.isAccount = '0';
  }
  isWrong();
}

/** 获取字典备注类型选项 */
function getRemarkOptions() {
  findYwDictList("flowRemark").then(response => {
    remarkOptions.value = response.data || [];
  });
}

/** 字典备注选择变更处理 */
function handleRemarkChange(value) {
  const selectedRemark = remarkOptions.value.find(item => item.ids === String(value));
  if (selectedRemark) {
    form.value.remark = selectedRemark.dictName;
    form.value.isRemark = '1';
  } else {
    form.value.remark = '';
    form.value.isRemark = '0';
  }
  isWrong();
}

/** 2个类型变更后调用该方法，判断是否一致了 */
function isWrong() {
  if(form.value.isRemark==='1' && form.value.isAccount==='1'){
    form.value.noWrong = '1';
  }else{
    form.value.noWrong = '0';
  }
}

/** 查询总流水列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeFlowDate.value && '' != daterangeFlowDate.value) {
    queryParams.value.params["beginFlowDate"] = daterangeFlowDate.value[0];
    queryParams.value.params["endFlowDate"] = daterangeFlowDate.value[1];
  }
  listFlow(queryParams.value).then(response => {
    flowList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    ids: null,
    accountId: null,
    accountName: null,
    isAccount: null,
    flowDate: null,
    abstracts: null,
    flowBorrow: null,
    flowLoan: null,
    remarkId: null,
    remark: null,
    isRemark: null,
    level2Flow: null,
    noWrong: null,
    addTime: null,
    upTime: null
  };
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeFlowDate.value = [];
  proxy.resetForm("queryFormRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.ids);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加总流水";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.ids || ids.value[0];
  getFlow(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改总流水";
  });
}

/** 提交按钮 */
function submitForm() {
  formRef.value.validate(valid => {
    if (valid) {
      if (form.value.ids != null) {
        updateFlow(form.value).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFlow(form.value).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idss = row.ids || ids.value;
  ElMessageBox.confirm('是否确认删除总流水编号为"' + idss + '"的数据项？', "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(function() {
      return delFlow(idss);
    }).then(() => {
      getList();
      ElMessage.success("删除成功");
    }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('work/flow/export', {
    ...queryParams.value
  }, `flow_${new Date().getTime()}.xlsx`);
}

/**导入excel表*/
function handleImport() {
  upload.value.titleImport = "导入流水合计表";
  upload.value.openImport = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('work/flow/importTemplate', {
    ...queryParams.value
  }, `流水合计模板_${new Date().getTime()}.xlsx`);
}

// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true;
}

// 文件上传成功处理
function handleFileSuccess(response, file, fileList) {
  upload.value.openImport = false;
  upload.value.isUploading = false;
  uploadRef.value.clearFiles();
  ElMessageBox.alert(response.msg, "导入结果", {
    dangerouslyUseHTMLString: true
  });
  getList();
}

// 提交上传文件
function submitFileForm() {
  uploadRef.value.submit();
}

onMounted(() => {
  getList();
  getAccountOptions();
  getRemarkOptions();
});
</script>